#!./bin/python
# ----------------------------------------------------------------------
# Fix broken pip versions
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------

# Python modules
import os
import sys
import subprocess
import tempfile

GET_PIP_DISTRIBUTION = "https://bootstrap.pypa.io/get-pip.py"


def get_pip_path():
    return os.path.join(os.getcwd(), "bin", "pip")


def is_pip_installed():
    """
    Check if pip installed
    """
    return os.path.exists(get_pip_path())


def get_pip_version():
    """
    Returns virtualenv's pip version
    """
    r = subprocess.check_output([
        get_pip_path(), "--version"
    ])
    _, version, _ = r.split(" ", 2)
    return version


def is_broken_version(v):
    """
    Check whether virtualenv is provided with broken version,
    which must be replaced
    """
    parts = v.split(".")
    major = int(parts[0])
    # minor = int(parts[1])
    return major < 8


def fix_pip():
    """
    Get last PIP version via get-pip
    """
    # Fetch get-pip
    with tempfile.NamedTemporaryFile() as script:
        subprocess.check_call(["curl", "-o", script.name, GET_PIP_DISTRIBUTION])
        subprocess.check_call([sys.executable, script.name])


def main():
    if is_pip_installed():
        v = get_pip_version()
        if is_broken_version(v):
            fix_pip()
            print("CHANGED")
        else:
            print("OK")
    else:
        fix_pip()
        print("CHANGED")


if __name__ == "__main__":
    main()
